#include "FileSender.h"
#include <QDebug>

#define BUF_SIZE 1024

FileSender::FileSender()
{

}

FileSender::~FileSender()
{
	if (_thread != NULL)
		delete _thread;
}

bool FileSender::Initialize(QHostAddress addr, int port, QString filePath)
{
	bool init = false;
	_fp = fopen(filePath.toAscii().data(), "rb");
	if (_fp != NULL)
	{
		_thread = new QThread;
		if (_thread != NULL)
		{
			_addr = addr;
			_port = port;
			connect(this, SIGNAL(readyRead()), this, SLOT(ProcessResponse()));
			connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(SocketState(QAbstractSocket::SocketState)));
			connect(this, SIGNAL(connected()), this, SLOT(Start()));
			_fInfo.setFile(filePath);
			SetKey(_addr, _fInfo.fileName());
			connectToHost(_addr, port);
			moveToThread(_thread);
			_thread->start();
			init = true;
		}
		else
			qDebug() << "FileSEnder::Initialize() : not enough memory.";
	}
	else
		qDebug() << "FileSender::Initialize() : file not found.";
	return init;
}

FileKey FileSender::GetKey()
{
	return _key;
}

void FileSender::Start()
{
	QByteArray request;
	request.append("SEND;");
	request.append(_fInfo.fileName());
	request.append(";");

	qint64 size = _fInfo.size();
	if (size < 1000)
		size = 0;
	else
	{
		qint64 rem = size % 1000ll;
		if (rem)
			size += (1000 - rem);
	}

	request.append(QString::number(size));
	request.append(";\n");
	if (write(request) == -1)
		emit sigError(_key, "FileSender::Start() : write() failed");
	else
		emit sigStarted(_key, _fInfo.size());
}

void FileSender::SendFile()
{
	bool fin = false;
	char buf[BUF_SIZE];
	int nbyte;

	while(!fin && !feof(_fp))
	{
		nbyte = fread(buf, 1, BUF_SIZE, _fp);
		if (nbyte > 0 && ferror(_fp) == 0)
		{
			if (write(buf, nbyte) != nbyte)
				fin = true;
			else
				emit sigFileSent(_key, nbyte);
		}
		else
			fin = true;
	}
	if (fin)
		emit sigError(_key, "FileSender::SendFile() error");
	else
		emit sigComplete(_key);
	Stop();
}

void FileSender::SetKey(QHostAddress addr, QString fileName, Mode mode)
{
	_key.Set(fileName, addr, mode);
}

void FileSender::Stop()
{
	disconnectFromHost();
	fclose(_fp);
}

void FileSender::ProcessResponse()
{
	QByteArray stream = readAll();
	if (stream.contains("OK"))
		SendFile();
	else
		Stop();
}

void FileSender::SocketState(QAbstractSocket::SocketState /*state*/)
{
//	qDebug() << "FileSender socket state : " << state;
}
